{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Bio.PopGen: Population genetics"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Bio.PopGen is a Biopython module supporting population genetics, available in Biopython 1.44 onwards.\n",
    "\n",
    "The medium term objective for the module is to support widely used data formats, applications and databases. This module is currently under intense development and support for new features should appear at a rather fast pace. Unfortunately this might also entail some instability on the API, especially if you are using a development version. APIs that are made available on our official public releases should be much more stable."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## GenePop"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "GenePop (http://genepop.curtin.edu.au/) is a popular population genetics software package supporting Hardy-Weinberg tests, linkage desiquilibrium, population diferentiation, basic statistics, Fst and migration estimates, among others. GenePop does not supply sequence based statistics as it doesn’t handle sequence data. The GenePop file format is supported by a wide range of other population genetic software applications, thus making it a relevant format in the population genetics field.\n",
    "\n",
    "Bio.PopGen provides a parser and generator of GenePop file format. Utilities to manipulate the content of a record are also provided. Here is an example on how to read a GenePop file (you can find example GenePop data files in the Test/PopGen directory of Biopython):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from copy import deepcopy\n",
    "from Bio.PopGen import GenePop\n",
    "\n",
    "handle = open(\"data/example.gen\")\n",
    "master_rec = GenePop.read(handle)\n",
    "handle.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This will read a file called example.gen and parse it. If you do print rec, the record will be output again, in GenePop format.\n",
    "\n",
    "The most important information in rec will be the loci names and population information (but there is more – use help(GenePop.Record) to check the API documentation). Loci names can be found on rec.loci_list. Population information can be found on rec.populations. Populations is a list with one element per population. Each element is itself a list of individuals, each individual is a pair composed by individual name and a list of alleles (2 per marker), here is an example for rec.populations:\n",
    "\n",
    "```python\n",
    "[\n",
    "    [\n",
    "        ('Ind1', [(1, 2),    (3, 3), (200, 201)],\n",
    "        ('Ind2', [(2, None), (3, 3), (None, None)],\n",
    "    ],\n",
    "    [\n",
    "        ('Other1', [(1, 1),  (4, 3), (200, 200)],\n",
    "    ]\n",
    "]\n",
    "```\n",
    "\n",
    "So we have two populations, the first with two individuals, the second with only one. The first individual of the first population is called Ind1, allelic information for each of the 3 loci follows. Please note that for any locus, information might be missing (see as an example, Ind2 above).\n",
    "\n",
    "A few utility functions to manipulate GenePop records are made available, here is an example:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Operations on GenePop records"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total populations 3\n",
      "After remove 2\n"
     ]
    }
   ],
   "source": [
    "print('Total populations %d' % len(master_rec.populations))\n",
    "rec = deepcopy(master_rec)\n",
    "pos = 0\n",
    "rec.remove_population(pos)\n",
    "print('After remove %d' % len(rec.populations))\n",
    "#Removes a population from a record, pos is the population position in\n",
    "#  rec.populations, remember that it starts on position 0.\n",
    "#  rec is altered."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loci names: loci1, another, and finally\n",
      "After removal: another, and finally\n"
     ]
    }
   ],
   "source": [
    "print('Loci names: %s' %  ', '.join(master_rec.loci_list))\n",
    "rec = deepcopy(master_rec)\n",
    "pos = 0\n",
    "rec.remove_locus_by_position(pos)\n",
    "print('After removal: %s' %  ', '.join(rec.loci_list))\n",
    "#Removes a locus by its position, pos is the locus position in\n",
    "#  rec.loci_list, remember that it starts on position 0.\n",
    "#  rec is altered.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "name = 'loci1'\n",
    "rec.remove_locus_by_name(name)\n",
    "#Removes a locus by its name, name is the locus name as in\n",
    "#  rec.loci_list. If the name doesn't exist the function fails\n",
    "#  silently.\n",
    "#  rec is altered."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "rec_loci = rec.split_in_loci(master_rec)\n",
    "#Splits a record in loci, that is, for each loci, it creates a new\n",
    "#  record, with a single loci and all populations.\n",
    "#  The result is returned in a dictionary, being each key the locus name.\n",
    "#  The value is the GenePop record.\n",
    "#  rec is not altered."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "pop_names = ['pop1', 'pop2', 'pop3']\n",
    "rec_pops = rec.split_in_pops(pop_names)\n",
    "#Splits a record in populations, that is, for each population, it creates\n",
    "#  a new record, with a single population and all loci.\n",
    "#  The result is returned in a dictionary, being each key\n",
    "#  the population name. As population names are not available in GenePop,\n",
    "#  they are passed in array (pop_names).\n",
    "#  The value of each dictionary entry is the GenePop record.\n",
    "#  rec is not altered."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "GenePop does not support population names, a limitation which can be cumbersome at times. Functionality to enable population names is currently being planned for Biopython. These extensions won’t break compatibility in any way with the standard format. In the medium term, we would also like to support the GenePop web service."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Coalescent simulation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A coalescent simulation is a backward model of population genetics with relation to time. A simulation of ancestry is done until the Most Recent Common Ancestor (MRCA) is found. This ancestry relationship starting on the MRCA and ending on the current generation sample is sometimes called a genealogy. Simple cases assume a population of constant size in time, haploidy, no population structure, and simulate the alleles of a single locus under no selection pressure.\n",
    "\n",
    "Coalescent theory is used in many fields like selection detection, estimation of demographic parameters of real populations or disease gene mapping.\n",
    "\n",
    "The strategy followed in the Biopython implementation of the coalescent was not to create a new, built-in, simulator from scratch but to use an existing one, SIMCOAL2 (http://cmpg.unibe.ch/software/simcoal2/). SIMCOAL2 allows for, among others, population structure, multiple demographic events, simulation of multiple types of loci (SNPs, sequences, STRs/microsatellites and RFLPs) with recombination, diploidy multiple chromosomes or ascertainment bias. Notably SIMCOAL2 doesn’t support any selection model. We recommend reading SIMCOAL2’s documentation, available in the link above.\n",
    "\n",
    "The input for SIMCOAL2 is a file specifying the desired demography and genome, the output is a set of files (typically around 1000) with the simulated genomes of a sample of individuals per subpopulation. This set of files can be used in many ways, like to compute confidence intervals where which certain statistics (e.g., Fst or Tajima D) are expected to lie. Real population genetics datasets statistics can then be compared to those confidence intervals.\n",
    "\n",
    "Biopython coalescent code allows to create demographic scenarios and genomes and to run SIMCOAL2."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Creating scenarios"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Creating a scenario involves both creating a demography and a chromosome structure. In many cases (e.g. when doing Approximate Bayesian Computations – ABC) it is important to test many parameter variations (e.g. vary the effective population size, Ne, between 10, 50, 500 and 1000 individuals). The code provided allows for the simulation of scenarios with different demographic parameters very easily.\n",
    "\n",
    "Below we see how we can create scenarios and then how simulate them."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "####  Demography"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A few predefined demographies are built-in, all have two shared parameters: sample size (called sample_size on the template, see below for its use) per deme and deme size, i.e. subpopulation size (pop_size). All demographies are available as templates where all parameters can be varied, each template has a system name. The prefedined demographies/templates are:\n",
    "\n",
    "**Single population, constant size**\n",
    "The standard parameters are enough to specify it. Template name: simple.\n",
    "\n",
    "**Single population, bottleneck**\n",
    "As seen on the figure below. The parameters are current population size (pop_size on template ne3 on figure), time of expansion, given as the generation in the past when it occurred (expand_gen), effective population size during bottleneck (ne2), time of contraction (contract_gen) and original size in the remote past (ne3). Template name: bottle.\n",
    "\n",
    "**Island model**\n",
    "The typical island model. The total number of demes is specified by total_demes and the migration rate by mig. Template name island.\n",
    "\n",
    "**Stepping stone model - 1 dimension**\n",
    "The stepping stone model in 1 dimension, extremes disconnected. The total number of demes is total_demes, migration rate is mig. Template name is ssm_1d.\n",
    "\n",
    "**Stepping stone model - 2 dimensions**\n",
    "The stepping stone model in 2 dimensions, extremes disconnected. The parameters are x for the horizontal dimension and y for the vertical (being the total number of demes x times y), migration rate is mig. Template name is ssm_2d."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#FIGURE HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In our first example, we will generate a template for a single population, constant size model with a sample size of 30 and a deme size of 500. The code for this is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from Bio.PopGen.SimCoal.Template import generate_simcoal_from_template\n",
    "\n",
    "generate_simcoal_from_template('simple',\n",
    "    [(1, [('SNP', [24, 0.0005, 0.0])])],\n",
    "    [('sample_size', [30]),\n",
    "    ('pop_size', [100])])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Executing this code snippet will generate a file on the current directory called simple_100_300.par this file can be given as input to SIMCOAL2 to simulate the demography (below we will see how Biopython can take care of calling SIMCOAL2).\n",
    "\n",
    "This code consists of a single function call, let’s discuss it parameter by parameter.\n",
    "\n",
    "The first parameter is the template id (from the list above). We are using the id ’simple’ which is the template for a single population of constant size along time.\n",
    "\n",
    "The second parameter is the chromosome structure. Please ignore it for now, it will be explained in the next section.\n",
    "\n",
    "The third parameter is a list of all required parameters (recall that the simple model only needs sample_size and pop_size) and possible values (in this case each parameter only has a possible value).\n",
    "\n",
    "Now, let’s consider an example where we want to generate several island models, and we are interested in varying the number of demes: 10, 50 and 100 with a migration rate of 1%. Sample size and deme size will be the same as before. Here is the code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from Bio.PopGen.SimCoal.Template import generate_simcoal_from_template\n",
    "\n",
    "generate_simcoal_from_template('island',\n",
    "    [(1, [('SNP', [24, 0.0005, 0.0])])],\n",
    "    [('sample_size', [30]),\n",
    "    ('pop_size', [100]),\n",
    "    ('mig', [0.01]),\n",
    "    ('total_demes', [10, 50, 100])])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this case, 3 files will be generated: island_100_0.01_100_30.par, island_10_0.01_100_30.par and island_50_0.01_100_30.par. Notice the rule to make file names: template name, followed by parameter values in reverse order.\n",
    "\n",
    "A few, arguably more esoteric template demographies exist (please check the Bio/PopGen/SimCoal/data directory on Biopython source tree). Furthermore it is possible for the user to create new templates. That functionality will be discussed in a future version of this document."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Chromosome structure"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We strongly recommend reading SIMCOAL2 documentation to understand the full potential available in modeling chromosome structures. In this subsection we only discuss how to implement chromosome structures using the Biopython interface, not the underlying SIMCOAL2 capabilities.\n",
    "\n",
    "We will start by implementing a single chromosome, with 24 SNPs with a recombination rate immediately on the right of each locus of 0.0005 and a minimum frequency of the minor allele of 0. This will be specified by the following list (to be passed as second parameter to the function generate_simcoal_from_template):\n",
    "\n",
    "```python\n",
    "[(1, [('SNP', [24, 0.0005, 0.0])])]```\n",
    "\n",
    "This is actually the chromosome structure used in the above examples.\n",
    "\n",
    "The chromosome structure is represented by a list of chromosomes, each chromosome (i.e., each element in the list) is composed by a tuple (a pair): the first element is the number of times the chromosome is to be repeated (as there might be interest in repeating the same chromosome many times). The second element is a list of the actual components of the chromosome. Each element is again a pair, the first member is the locus type and the second element the parameters for that locus type. Confused? Before showing more examples let’s review the example above: We have a list with one element (thus one chromosome), the chromosome is a single instance (therefore not to be repeated), it is composed of 24 SNPs, with a recombination rate of 0.0005 between each consecutive SNP, the minimum frequency of the minor allele is 0.0 (i.e, it can be absent from a certain population).\n",
    "\n",
    "Let's see a more complicated example:\n",
    "\n",
    "```python\n",
    "[\n",
    "  (5, [\n",
    "       ('SNP', [24, 0.0005, 0.0])\n",
    "      ]\n",
    "  ),\n",
    "  (2, [\n",
    "       ('DNA', [10, 0.0, 0.00005, 0.33]),\n",
    "       ('RFLP', [1, 0.0, 0.0001]),\n",
    "       ('MICROSAT', [1, 0.0, 0.001, 0.0, 0.0])\n",
    "      ]\n",
    "  )\n",
    "]\n",
    "```\n",
    "\n",
    "We start by having 5 chromosomes with the same structure as above (i.e., 24 SNPs). We then have 2 chromosomes which have a DNA sequence with 10 nucleotides, 0.0 recombination rate, 0.0005 mutation rate, and a transition rate of 0.33. Then we have an RFLP with 0.0 recombination rate to the next locus and a 0.0001 mutation rate. Finally we have a microsatellite (or STR), with 0.0 recombination rate to the next locus (note, that as this is a single microsatellite which has no loci following, this recombination rate here is irrelevant), with a mutation rate of 0.001, geometric parameter of 0.0 and a range constraint of 0.0 (for information about this parameters please consult the SIMCOAL2 documentation, you can use them to simulate various mutation models, including the typical – for microsatellites – stepwise mutation model among others)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Running SIMCOAL2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now discuss how to run SIMCOAL2 from inside Biopython. It is required that the binary for SIMCOAL2 is called simcoal2 (or simcoal2.exe on Windows based platforms), please note that the typical name when downloading the program is in the format simcoal2_x_y. As such, when installing SIMCOAL2 you will need to rename of the downloaded executable so that Biopython can find it.\n",
    "\n",
    "It is possible to run SIMCOAL2 on files that were not generated using the method above (e.g., writing a parameter file by hand), but we will show an example by creating a model using the framework presented above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from Bio.PopGen.SimCoal.Template import generate_simcoal_from_template\n",
    "from Bio.PopGen.SimCoal.Controller import SimCoalController\n",
    "\n",
    "\n",
    "generate_simcoal_from_template('simple',\n",
    "    [\n",
    "      (5, [\n",
    "           ('SNP', [24, 0.0005, 0.0])\n",
    "          ]\n",
    "      ),\n",
    "      (2, [\n",
    "           ('DNA', [10, 0.0, 0.00005, 0.33]),\n",
    "           ('RFLP', [1, 0.0, 0.0001]),\n",
    "           ('MICROSAT', [1, 0.0, 0.001, 0.0, 0.0])\n",
    "          ]\n",
    "      )\n",
    "    ],\n",
    "    [('sample_size', [30]),\n",
    "    ('pop_size', [100])])\n",
    "\n",
    "#Simcoal not installed in the tutorial\n",
    "#ctrl = SimCoalController('.')\n",
    "#ctrl.run_simcoal('simple_100_30.par', 50)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The lines of interest are the last two (plus the new import). Firstly a controller for the application is created. The directory where the binary is located has to be specified.\n",
    "\n",
    "The simulator is then run on the last line: we know, from the rules explained above, that the input file name is simple_100_30.par for the simulation parameter file created. We then specify that we want to run 50 independent simulations, by default Biopython requests a simulation of diploid data, but a third parameter can be added to simulate haploid data (adding as a parameter the string ’0’). SIMCOAL2 will now run (please note that this can take quite a lot of time) and will create a directory with the simulation results. The results can now be analysed (typically studying the data with Arlequin3). In the future Biopython might support reading the Arlequin3 format and thus allowing for the analysis of SIMCOAL2 data inside Biopython."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
